Dynamic memory

The application can allocate memory at runtime instead of compile time thanks to C++'s dynamic memory allocation feature. When you don't know how much memory is required until the program is running, this is helpful.

In C++, the new and delete operators are used to control dynamic memory:

Memory is allocated on the heap using new, which also returns a pointer to the memory that has been allocated.
To deallocate memory that was previously allocated with new, use delete.

A sample program on Dynamic memory:
#include <iostream>
using namespace std;

int main() {
    // Dynamic memory allocation for an integer using 'new'
    int *ptr = new int;   // Allocate memory for an integer
    *ptr = 100;           // Assign a value to the allocated memory

    // Output the value stored in the dynamically allocated memory
    cout << "Value stored at ptr: " << *ptr << endl;

    // Dynamic memory allocation for an array of integers
    int *arr = new int[5]; // Allocate memory for an array of 5 integers

    // Assign values to the array
    for(int i = 0; i < 5; i++) {
        arr[i] = (i + 1) * 10;  // Assign multiples of 10 to the array
    }

    // Output the values stored in the array
    cout << "Values in the dynamically allocated array: ";
    for(int i = 0; i < 5; i++) {
        cout << arr[i] << " ";
    }
    cout << endl;

    // Deallocate memory using 'delete' for a single variable
    delete ptr;  // Free the memory allocated for the single integer

    // Deallocate memory using 'delete[]' for the array
    delete[] arr; // Free the memory allocated for the array

    return 0;
}

Summary:
Allocation of a single variable (new int):
We use new int to allocate memory for a single integer.
Following allocation, we give the memory a value of 100.
The value that is stored in that memory is output.

Allocating an array (new int[5]):
We use new int[5] to allocate memory for an array of five integers.
We display the values that we have assigned to the array (multiples of 10).

Deallocation
To deallocate the memory for the single integer, use delete ptr.
delete[] arr; releases all of the array's memory. Note that arrays are deleted using delete[] whereas a single variable is deleted using delete

Points to remember:
Memory allocated by new is stored on the heap until it is specifically released using delete.
Whereas delete[] is used for arrays, delete releases the memory allotted for a single object.
To avoid memory leaks, deallocate memory whenever you're finished.

← Back Next →

Comments

Popular posts from this blog

Wrapper Class

Information Security & Essential Terminology

Information Security Threat Categories